// Copyright (c) Microsoft Corporation. All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Transactions;

namespace Microsoft.TeamFoundation.Migration.Toolkit
{
    public class MigrationSqlTransaction : MigrationTransaction
    {
        SqlConnection m_conn;
        SqlTransaction m_tran;

        bool m_isComplete;

        internal MigrationSqlTransaction()
        {
            m_conn = DataAccessManager.Current.GetSqlConnection();
            m_conn.Open();

            m_tran = m_conn.BeginTransaction();
        }

        public override void Complete()
        {
            m_tran.Commit();
            m_isComplete = true;
        }

        public SqlCommand CreateCommand()
        {
            SqlCommand cmd = m_conn.CreateCommand();
            cmd.Transaction = m_tran;

            return cmd;
        }


        protected override void Dispose(bool disposing)
        {
            try
            {
                base.Dispose(disposing);
            }
            finally
            {
                if (disposing)
                {
                    try
                    {
                        if (!m_isComplete)
                        {
                            m_tran.Rollback();
                        }

                        m_tran.Dispose();
                    }
                    finally
                    {
                        m_conn.Dispose();
                    }
                }
            }
        }
    }
}
